﻿using Common;
using GameStates;
using UnityEngine;

namespace Actors
{
    public class CharacterVisual : ActorVisual
    {
        private Animator m_Animator;
        private Character m_Character;
        private readonly StateMachine m_AnimationStateMachine = new StateMachine();

        
        public CharacterVisual(Actor owner) : base(owner)
        {
            InitAnimator();
            m_Character = owner as Character;
        }
        
        private void InitAnimator()
        {
            m_Animator = gameObject.AddComponent<Animator>();
            m_Animator.runtimeAnimatorController = ResourceLoader.Load<RuntimeAnimatorController>("Animations/AC");
        }

        public void Update()
        {
            m_AnimationStateMachine.Update();
        }

        public void PlayAnimation(string stateName)
        {
            m_Animator.Play(stateName);
        }

        #region Character Animation States

        private void ChangeState(CharacterAnimationStates state)
        {
            state.Initialize(m_Character);
            m_AnimationStateMachine.ChangeState(state);
        }
        
        public void OnActionIdle()
        {
            var idleAnimState = StatePool.Get<CAS_Idle>();
            ChangeState(idleAnimState);
        }
        
        public void OnActionMove()
        {
            var runAnimState = StatePool.Get<CAS_Move>();
            ChangeState(runAnimState);
        }
        
        public void OnActionJump()
        {
            var jumpAnimState = StatePool.Get<CAS_Jump>();
            ChangeState(jumpAnimState);
        }
        
        public void OnActionFall()
        {
            var fallAnimState = StatePool.Get<CAS_Fall>();
            ChangeState(fallAnimState);
        }
        
        public void OnActionLand()
        {
            var landAnimState = StatePool.Get<CAS_Land>();
            ChangeState(landAnimState);
        }
        

        #endregion
    }
}